package com.example.byd

import android.Manifest
import android.content.*
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.PixelFormat
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.WindowManager
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.content.FileProvider
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.byd.databinding.ActivityMainBinding
import com.google.android.material.bottomnavigation.BottomNavigationView
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream


class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val navView: BottomNavigationView = binding.navView

        val navController = findNavController(R.id.nav_host_fragment_activity_main)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        val appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications
            )
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)


        startService(Intent(baseContext, GetLogCatService::class.java))
        val permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS)




        requestPermissions(permissions,1)
        //申请权限之后 其实还不能创建目录，需要调用  obbDir 这个逼玩意，要不比亚迪车机创建不上。妈蛋 坑了我4个小时

        var hasp= baseContext.checkSelfPermission(Manifest.permission.READ_LOGS)
        if (hasp == PackageManager.PERMISSION_DENIED){
            Log.i("bydautosong","还是没有权限")
            Toast.makeText(baseContext, "还是没有权限", Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(baseContext, "获得系统日志读取权限", Toast.LENGTH_LONG).show();
            Log.i("bydautosong","获得系统日志读取权限")

        }


    }


    fun open_setting(view: View) {
        Log.i("bydautosong","ananan")

        val intent = Intent(this, SettingsActivity::class.java)
        startActivity(intent)

    }


    fun remoteeye(view: View){
        Log.i("bydautosong","ananan")

        val intent = Intent(this, rtc::class.java)
        startActivity(intent)


    }

    fun install(path:String){


        val apk = File(path)
        val intent = Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //注意第二个参数，要保持和manifest中android:authorities的值相同
            val uri = FileProvider.getUriForFile(baseContext,baseContext.getPackageName()+".fileprovider",apk);
            Log.e("bydautosong", "url shi"+uri)
            intent.setDataAndType(uri, "application/vnd.android.package-archive");

        } else {
            intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive");
        }
        try {
            baseContext.startActivity(intent);
        } catch (e: Exception) {
            e.printStackTrace();
        }
    }


    /**
     * 复制文件到SD卡
     * @param context
     * @param fileName 复制的文件名
     * @param path  保存的目录路径
     * @return
     */
    fun copyAssetsFile(context :android.content.Context, fileName: String, path: String): Uri? {
        return try {
            val mInputStream: InputStream = context.getAssets().open(fileName)
            val file = File(path)
            if (!file.exists()) {
                file.mkdir()
            }
            val mFile = File(path + File.separator + fileName)
            if (!mFile.exists()) mFile.createNewFile()
            Log.e("bydautosong", "开始拷贝")
            val mFileOutputStream = FileOutputStream(mFile)
            val mbyte = ByteArray(1024)
            var i = 0
            while (mInputStream.read(mbyte).also { i = it } > 0) {
                mFileOutputStream.write(mbyte, 0, i)
            }
            mInputStream.close()
            mFileOutputStream.close()
            var uri: Uri? = null
            try {
                uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //包名.fileprovider
                    FileProvider.getUriForFile(context, "com.example.byd.fileprovider", mFile)
                } else {
                    Uri.fromFile(mFile)
                }
            } catch (anfe: ActivityNotFoundException) {
                anfe.message?.let { Log.e("bydautosong", it) }
            }
            MediaScannerConnection.scanFile(context, arrayOf(mFile.absolutePath), null, null)
            Log.e("bydautosong", "拷贝完毕：$uri")
            uri
        } catch (e: IOException) {
            e.printStackTrace()
            Log.e("bydautosong", fileName + "not exists" + "or write err")
            null
        } catch (e: java.lang.Exception) {
            null
        }
    }


    fun  hasPermission(context: Context, permission:String): Boolean {
        return context.checkCallingOrSelfPermission(permission)== PackageManager.PERMISSION_GRANTED;
    }






    fun instaljkc(view: View) {
        Log.i("bydautosong","开始安装甲壳虫 ${baseContext.assets}")
       copyAssetsFile(baseContext,"jiakechong.apk",obbDir.toString())
       install("${obbDir.toString()}/jiakechong.apk")
    }


    fun QuickShortcutMaker(view: View) {

        Log.i("bydautosong","开始安装tasker ${obbDir}")
        copyAssetsFile(baseContext,"tasker.apk",obbDir.toString())
        install("${obbDir.toString()}/tasker.apk")
    }


    fun instalxiaoai(view: View) {

        Log.i("bydautosong","开始安装xiaomixiaoai ${obbDir}")
        copyAssetsFile(baseContext,"xiaomixiaoai.apk",obbDir.toString())
        install("${obbDir.toString()}/xiaomixiaoai.apk")
    }

    fun instalaudioservice(view: View) {
//        Toast.makeText(baseContext, "不支持讯飞语音", Toast.LENGTH_LONG).show();
        Log.i("bydautosong","开始安装audioservice ${obbDir}")
        copyAssetsFile(baseContext,"songjiaaudioservice.apk",obbDir.toString())
        install("${obbDir.toString()}/songjiaaudioservice.apk")
    }




    fun toustdebug(view: View) {
        Log.i("bydautosong","开始跳转开发者选项")

//        val intent = Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
//        startActivity(intent)


        Log.i("bydautosong","开始跳自启动管理")

        val componetName = ComponentName(
            "com.byd.byddevelopmenttools",  //这个是另外一个应用程序的包名
            "com.byd.byddevelopmenttools.ADBSettingsActivity"
        )

        try {
            val intent = Intent()
            intent.component = componetName
            startActivity(intent)
        } catch (e: java.lang.Exception) {
            Toast.makeText(this, "跳转异常，请检查跳转配置、包名及Activity访问权限", Toast.LENGTH_SHORT).show()
        }


    }
    fun adbwireless(view: View){
        //        dumpsys window | grep mCurrentFocus  adb获取当前的activity
        Log.i("bydautosong","开始转跳无线自启动")
        val componetName = ComponentName(
            "com.byd.byddevelopmenttools",  //这个是另外一个应用程序的包名
            "com.byd.byddevelopmenttools.LogControlAndTestToolsActivity"
        )
        try {
            val intent = Intent()
            intent.component = componetName
            startActivity(intent)
        } catch (e: java.lang.Exception) {
            Toast.makeText(this, "跳转异常，请检查跳转配置、包名及Activity访问权限", Toast.LENGTH_SHORT).show()
        }
    }

    fun openjiakechong(view: View){
        Log.i("bydautosong","开始转跳甲壳虫")
        val packageName="com.didjdk.adbhelper"
        val intent = baseContext.packageManager.getLaunchIntentForPackage(packageName)
        if (intent != null) {
            baseContext.startActivity(intent)
        } else {
            Log.e("TAG", "${packageName}包名不存在")

        }

    }

    fun copycmd(view: View){
        Log.i("bydautosong","写入剪切板")

        copyAssetsFile(baseContext,"雷达测距.prf.xml",obbDir.toString())
        copyAssetsFile(baseContext,"雷达距离.scn.xml",obbDir.toString())
        copyAssetsFile(baseContext,"雷达距离竖屏.scn.xml",obbDir.toString())
        copyAssetsFile(baseContext,"强删场景.prf.xml",obbDir.toString())


        val mClipData = ClipData.newPlainText("Label", "mkdir -p /storage/emulated/0/Tasker/scenes\nmkdir -p /storage/emulated/0/Tasker/profiles\ncp /storage/emulated/0/Android/obb/com.example.byd/* /storage/emulated/0/Tasker/profiles\n" +
                "cp /storage/emulated/0/Android/obb/com.example.byd/* /storage/emulated/0/Tasker/scenes\npm grant com.example.byd android.permission.READ_LOGS\npm grant net.dinglisch.android.taskerm android.permission.WRITE_SECURE_SETTINGS\npm grant net.dinglisch.android.taskerm android.permission.READ_LOGS\nappops set net.dinglisch.android.taskerm SYSTEM_ALERT_WINDOW allow")
        val manager = baseContext.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager

        manager.setPrimaryClip(mClipData);
        Toast.makeText(baseContext, "写入剪切板成功", Toast.LENGTH_LONG).show();
    }

    fun ziqidong(view: View){
        Log.i("bydautosong","开始转跳自启动")
        val componetName = ComponentName(
            "com.byd.appstartmanagement",  //这个是另外一个应用程序的包名
            "com.byd.appstartmanagement.frame.AppStartManagement"
        )
        try {
            val intent = Intent()
            intent.component = componetName
            startActivity(intent)
        } catch (e: java.lang.Exception) {
            Toast.makeText(this, "跳转异常，请检查跳转配置、包名及Activity访问权限", Toast.LENGTH_SHORT).show()
        }
    }

    fun closefuchuang(view: View){
        Log.i("BYDAutoInstrumentDevice","closefuchuang bydautosong")

    }

    fun shouquan(view: View){
        Log.i("bydautosong","开始转跳自启动授权")
        if (Settings.canDrawOverlays(this)) {
            Toast.makeText(this, "浮窗权限已授予", Toast.LENGTH_SHORT).show()
        } else {
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            intent.data = Uri.parse("package:$packageName")
            startActivity(intent)
        }


        Log.i("BYDAutoInstrumentDevice"," getAllRadarDistance format: left front is 左前, right front is 右前, left rear is 左后, right rear is 右后, left is 左侧, right is 右侧, front left is 左前1, front right is 右前1, middle rear radar is 后侧")

//        winmager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
//
//        val text1 = TextView(this)
//        text1.setText("按钮")
//        text1.textSize=30f
//        text1.setTextColor(Color.rgb(255, 0, 0))
////        button.setOnTouchListener(FloatingOnTouchListener())
////        text1.setOnClickListener(object : View.OnClickListener {
////            override fun onClick(p1: View?) {
////                Toast.makeText(application, "我被点击了", Toast.LENGTH_SHORT).show()
////            }
////        })
//        layoutParams = WindowManager.LayoutParams(
//            WindowManager.LayoutParams.WRAP_CONTENT,
//            WindowManager.LayoutParams.WRAP_CONTENT,
//            0,
//            0,
//            PixelFormat.TRANSPARENT
//        )
//        layoutParams!!.flags = (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
//                or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
//                or WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW)
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            layoutParams!!.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
//        } else {
//            layoutParams!!.type = WindowManager.LayoutParams.TYPE_PHONE
//        }
//
//        layoutParams!!.format = PixelFormat.RGBA_8888
//        layoutParams!!.gravity = Gravity.LEFT or Gravity.TOP
//        layoutParams!!.x = 300
//        layoutParams!!.y = 250
//
//
//
//        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
//            layoutParams!!.type =WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
//        }else{
//            layoutParams!!.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
//        }
//
//
//
//
//
//
//
//        winmager!!.addView(text1, layoutParams)
//
//
//
//
//        Thread.sleep(2000)
//
//        winmager!!.removeView(text1) 移除


    }

//拖动
//    private class FloatingOnTouchListener : OnTouchListener {
//        private var startX = 0
//        private var startY = 0
//        override fun onTouch(view: View, event: MotionEvent): Boolean {
//
//
//            when (event.action) {
//
//
//                MotionEvent.ACTION_DOWN -> {
//                    startX = event.rawX.toInt()
//                    startY = event.rawY.toInt()
//                }
//                MotionEvent.ACTION_MOVE -> {
//                    val nowX = event.rawX.toInt()
//                    val nowY = event.rawY.toInt()
//                    val movedX = nowX - startX
//                    val movedY = nowY - startY
//                    startX = nowX
//                    startY = nowY
//
//                    if (layoutParams != null) {
//                        layoutParams!!.x = layoutParams!!.x + movedX
//                    }
//                    if (layoutParams != null) {
//                        layoutParams!!.y = layoutParams!!.y + movedY
//                    }
//
//                    // 更新悬浮窗控件布局
//                    winmager?.updateViewLayout(view, layoutParams)
//                }
//                else -> {}
//            }
//            return false
//        }
//    }



}